//添加node.js 进程守护 可考虑PM2
const express = require("express");
const path = require("path");
const fs = require("fs");
const app = express();
var cookieParser = require('cookie-parser')
var compression = require('compression')
var bodyParser = require('body-parser');



app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(compression());
app.use(cookieParser());

// 跨域设置
app.all("*", function(req, res, next) {
	if (req.path !== "/" && !req.path.includes(".")) {
		res.header("Access-Control-Allmockow-Credentials", true);
		// 这里获取 origin 请求头 而不是用 *
		res.header("Access-Control-Allow-Origin", req.headers["origin"] || "*");
		res.header("Access-Control-Allow-Headers", "X-Requested-With");
		res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
		res.header("Content-Type", "application/json;charset=utf-8");
	}
	next();
});
app.get('/api/echo/test', (req, res) => {
	res.jsonp(req.query)
})
const Wrap = fn => (req, res) => fn(req, res);


// 同步读取 router 目录中的js文件, 根据命名规则, 自动注册路由

let readdirSync = (filePath,type='get')=>{
	fs.readdirSync(path.resolve(__dirname,filePath)).forEach(file => {
		let _isDir_ = fs.lstatSync(path.resolve(__dirname, filePath+file));
		if(_isDir_.isDirectory()){
			readdirSync(filePath+file+'/',file);
			// console.log(isDir,filePath+file)
		}else{

			if (/\.js$/i.test(file) === false) {
				return;
			}
			// 以 /api/ 开头 ，把file(每个文件的.js后缀替换掉)，把 _ 替换成 / ，以驼峰的形式定义的文件名，转换成 / 分割，并转换为小写
			// let route ="/huanghuisong/" +file.replace(/\.js$/i, "").replace(/_/g, "/").replace(/[A-Z]/g, a => {
			// 	return "/" + a.toLowerCase();
			// });

			let route ="/huanghuisong/" +file.replace(/\.js$/i, "").replace(/_/g, "/");
			// console.log(route,filePath + file);
			app[type||'get'](route, Wrap(require(filePath + file)));
		}
		// 	console.log(_isDir_)
	});
};

readdirSync('../routes/');
require('./error');

const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`server running @ http://localhost:${port}`);
});

module.exports = app;

